package org.yty.travelagencymongodb.service.impl;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.Entity.ChatGroupMember;
import org.yty.travelagencymongodb.repository.ChatGroupMemberRepository;
import org.yty.travelagencymongodb.service.ChatGroupMemberService;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ChatGroupMemberServiceImpl implements ChatGroupMemberService {
    private final ChatGroupMemberRepository chatGroupMemberRepository;
    private final MongoTemplate mongoTemplate;

    @Override
    public List<ChatGroupMember> getListByChatGroupId(String chatGroupId) {
        return this.mongoTemplate.find(new Query(Criteria.where("chatGroupId").is(chatGroupId)), ChatGroupMember.class);
    }

    @Override
    public boolean save(ChatGroupMember chatGroupMember) {
        if (chatGroupMember.getId() == null){
            chatGroupMember.setId(IdUtil.getSnowflakeNextId());
        }
        chatGroupMember.setCreateTime(LocalDateTime.now());
        chatGroupMember.setUpdateTime(LocalDateTime.now());
        chatGroupMember = this.chatGroupMemberRepository.insert(chatGroupMember);
        return chatGroupMember != null;
    }

    @Override
    public void deleteByChatGroupIdAndChatUserId(String chatGroupId, String chatUserId) {
        this.chatGroupMemberRepository.deleteByChatGroupIdAndChatUserId(chatGroupId, chatUserId);
    }

    @Override
    public void deleteByChatGroupId(String chatGroupId) {
        this.chatGroupMemberRepository.deleteByChatGroupId(chatGroupId);
    }

    @Override
    public void deleteByChatUserId(String chatUserId) {
        this.chatGroupMemberRepository.deleteByChatUserId(chatUserId);
    }
}
